# Create your views here.
from django.contrib.auth.decorators import login_required
from django.shortcuts import render

from dvadmin.utils.json_response import SuccessResponse
from dvadmin.utils.viewset import CustomModelViewSet
from ele_meter.models import CrudDemoModel
from ele_meter.serializers import CrudDemoModelSerializer, CrudDemoModelCreateUpdateSerializer


def get_user_data(user):
    # 这里根据用户信息获取数据，以下为示例
    if user.is_staff:
        return "Admin specific data"
    else:
        return "Regular user data"


@login_required
def new_page(request):
    user = request.user
    # 根据用户信息获取特定数据
    user_data = get_user_data(user)
    return render(request, 'index.html', {'user_data': user_data})


class CrudDemoModelViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = CrudDemoModel.objects.all()
    serializer_class = CrudDemoModelSerializer
    create_serializer_class = CrudDemoModelCreateUpdateSerializer
    update_serializer_class = CrudDemoModelCreateUpdateSerializer
    # filter_fields = ['meterNo', 'paramName', 'time']
    # search_fields = ['meterNo']


class StatDemoModelViewSet(CustomModelViewSet):
    queryset = CrudDemoModel.objects.all()
    serializer_class = CrudDemoModelSerializer
    create_serializer_class = CrudDemoModelCreateUpdateSerializer
    update_serializer_class = CrudDemoModelCreateUpdateSerializer
    filter_fields = ['meterNo', 'paramName', 'time']
    search_fields = ['meterNo']

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())[:1]
        # queryset修改不了
        queryset[0].meterNo = "123"
        serializer = self.get_serializer(queryset, many=True, request=request)
        serializer.data[0]['meterNo'] = "123"
        return SuccessResponse(data=serializer.data, msg="获取成功")
